<template>
  <div class="status-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="6">
          <el-form-item label="物料分类" prop="category">
            <el-select
              v-model="form.category"
              value-key="fid"
              placeholder="请选择物料分类"
              filterable
              @change="selectCategoryFun($event)"
            >
              <el-option
                v-for="item in categories"
                :key="item.fid"
                :label="item.fname"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="物料"
            prop="product"
            :element-loading-text="elementLoadingText"
          >
            <el-select
              v-model="form.product"
              value-key="fnumber"
              filterable
              :filter-method="filterMethod"
              placeholder="请选择物料"
              @visible-change="visibleChange"
              @change="selectProductFun($event)"
            >
              <el-option
                v-for="item in filterProducts"
                :key="item.fnumber"
                :label="item.fname"
                :value="item"
              >
                <span style="float: left">{{ item.fname }}</span>
                <span style="float: right; font-size: 13px; color: #8492a6">
                {{ item.fnumber }}
              </span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="规格型号">
            <el-input
              v-model.trim="form.specName"
              disabled
              placeholder="规格型号"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="基本单位">
            <el-input
              v-model.trim="form.fbaseUnitIdfname"
              disabled
              placeholder="基本单位"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" class="header_cond">
        <el-tab-pane label="价格策略" name="price">
          <div v-if="activeName === 'price'" class="header_cond_sub">
            <div class="header_cond_fix">
              <el-form-item label="价格" prop="price">
                <el-input v-model="form.price" autocomplete="off"></el-input>
              </el-form-item>
            </div>
            <div class="header_cond_part">
              <el-form-item label="料包">
                <el-checkbox v-model="form.liaobao"></el-checkbox>
              </el-form-item>
              <el-form-item label="特殊数量" prop="specNum" label-width="80px">
                <el-input-number v-model="form.specNum" :min="1" />
              </el-form-item>
              <el-form-item label="榨菜" label-width="60px">
                <el-checkbox v-model="form.zhacai"></el-checkbox>
              </el-form-item>
              <el-form-item label="辣椒油" label-width="65px">
                <el-checkbox v-model="form.lajiaoyou"></el-checkbox>
              </el-form-item>
              <el-form-item label="香葱" label-width="50px">
                <el-checkbox v-model="form.xiangcong"></el-checkbox>
              </el-form-item>
              <el-form-item label="小馄饨料粉" label-width="100px">
                <el-checkbox v-model="form.xiaohuntun"></el-checkbox>
              </el-form-item>
            </div>
            <div class="header_cond_btn">
              <el-button type="primary" @click="save">确 定</el-button>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="倍数起订量" name="count">
          <div v-if="activeName === 'count'" class="header_cond_sub">
            <div class="header_cond_fix">
              <el-form-item label="倍数" prop="step">
                <el-input-number v-model="form.moqTimes" :precision="0" :min="0"></el-input-number>
              </el-form-item>
            </div>
            <div class="header_cond_fix">
              <el-form-item label="起订量" prop="startCount">
                <el-input-number v-model="form.moq" :precision="0" :min="0"></el-input-number>
              </el-form-item>
            </div>
            <div class="header_cond_btn">
              <el-button type="primary" @click="saveMoq">确 定</el-button>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="暂停报货" name="stop">
          <div v-if="activeName === 'stop'" class="header_cond_sub">
            <div class="header_cond_fix">
              <el-form-item prop="stop">
                <el-switch v-model="form.stopSell" active-color="#46a6ff" inactive-color="#13ce66" active-text="暂停" inactive-text="开启"></el-switch>
              </el-form-item>
            </div>
            <div class="header_cond_btn">
              <el-button type="primary" @click="saveStopSell">确 定</el-button>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <el-row :gutter="20">
      <el-col :span="6">
        <strategy-list
          :checkbox="true"
          @strategy-info="getStrategyInfo"
          @selection-change="selectionChange"
        ></strategy-list>
      </el-col>
      <el-col :span="18">
        <el-row>
          <strategy-info ref="strategyInfo"></strategy-info>
        </el-row>
        <el-row>
          <el-col>
            <material-info ref="materialInfo"></material-info>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import StrategyList from './components/strategyList'
  import StrategyInfo from './components/strategyInfo'
  import MaterialInfo from './components/materialList'
  import { getCategoryList } from '@/api/erp'
  import { getSpecList } from '@/api/erp'
  import { doMultiSetPriceStrategy, doMultiSetMoqStrategy, doMultiSetStopSellStrategy } from '@/api/priceStrategyManagement'

  export default {
    name: 'MultiPriceStrategyManage',
    components: { StrategyList, MaterialInfo, StrategyInfo },
    data() {
      var checkCategory = (rule, value, callback) => {
        if (!value.fname) {
          return callback(new Error('请选择物料分类!'))
        }
        callback()
      }

      var checkProduct = (rule, value, callback) => {
        if (!value.fname) {
          return callback(new Error('请选择物料!'))
        }
        callback()
      }

      var checkPrice = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('价格不能为空!'))
        }
        if (isNaN(value)) {
          callback(new Error('请输入数字值!'))
        } else {
          if (value < 0) {
            callback(new Error('请输入正确的价格!'))
          } else {
            callback()
          }
        }
      }
      return {
        activeName: 'price',
        form: {
          category: {},
          product: {},
          specName: '',
          price: '',
          fbaseUnitIdfname: '',
          liaobao: false,
          zhacai: false,
          lajiaoyou: false,
          xiangcong: false,
          xiaohuntun: false,
          specNum: 1,
          moqTimes: 0,
          moq: 0,
          stopSell: false,
          strategyIds: [],
        },
        elementLoadingText: false,
        products: [],
        filterProducts: [],
        categories: [],
        currentSelectRow : null,
        rules: {
          category: [
            { required: true, trigger: 'blur', message: '请选择分类' },
            { validator: checkCategory, trigger: 'blur' },
          ],
          product: [
            { required: true, trigger: 'blur', message: '请选择物料' },
            { validator: checkProduct, trigger: 'blur' },
          ],
          price: [
            { required: true, trigger: 'blur', message: '请输入价格' },
            { validator: checkPrice, trigger: 'blur' },
          ],
        },
      }
    },
    created() {
      this.fetchData()
    },
    methods: {
      async fetchData() {
        this.categories = await getCategoryList()
      },
      getStrategyInfo(data) {
        this.currentSelectRow = data
        this.$refs['strategyInfo'].showPriceStrategyInfo(data)
        this.$refs['materialInfo'].showMateriaInfo(data)
      },
      async selectCategoryFun(event) {
        this.elementLoadingText = true
        this.form.product = {}
        this.form.fbaseUnitIdfname = ''
        this.form.specName = ''
        this.products = []
        this.products = await getSpecList(event.fid)
        this.filterProducts = this.products
        this.elementLoadingText = false
      },
      selectProductFun(event) {
        this.form.specName = event.fspecification
        this.form.fbaseUnitIdfname = event.fbaseUnitIdfname
      },
      filterMethod: function (query) {
        if (query != '') {
          this.filterProducts = this.products.filter((item) => {
            return (
              item.fname.toLowerCase().indexOf(query.toLowerCase()) > -1 ||
              item.fnumber.indexOf(query.toLowerCase()) > -1
            )
          })
        } else {
          this.filterProducts = this.products
        }
      },
      visibleChange: function (event) {
        if (event) {
          this.filterProducts = this.products
        }
      },
      selectionChange: function (val) {
        let ids = this.$baseLodash.map(val, 'id')
        this.strategyIds = ids
      },
      save: function () {
        let vm = this
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            let data = vm.form
            let postData = {
              strategyIds: this.strategyIds,
              item: {
                categoryCode: data.category.fid,
                categoryName: data.category.fname,
                productCode: data.product.fnumber,
                productName: data.product.fname,
                specCode: data.specCode,
                specNum: data.specNum,
                specName: data.product.fspecification,
                fbaseUnitIdfname: data.product.fbaseUnitIdfname,
                price: data.price,
                liaobao: data.liaobao,
                zhacai: data.zhacai,
                lajiaoyou: data.lajiaoyou,
                xiangcong: data.xiangcong,
                xiaohuntun: data.xiaohuntun
              }
            }
            await doMultiSetPriceStrategy(postData)
            this.$baseMessage('价格策略保存成功', 'success')

            //刷新被选择的价格策略
            this.$refs['materialInfo'].showMateriaInfo(this.currentSelectRow)

          } else {
            return false
          }
        })
      },
      // 起订量，倍数
      saveMoq() {
        let vm = this
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            let data = vm.form
            let postData = {
              strategyIds: this.strategyIds,
              item: {
                categoryCode: data.category.fid,
                categoryName: data.category.fname,
                productCode: data.product.fnumber,
                productName: data.product.fname,
                specCode: data.specCode,
                specNum: data.specNum,
                specName: data.product.fspecification,
                fbaseUnitIdfname: data.product.fbaseUnitIdfname,
                moqTimes: data.moqTimes,
                moq: data.moq
              },
            }
            await doMultiSetMoqStrategy(postData)
            this.$baseMessage('价格策略保存成功', 'success')

            //刷新被选择的价格策略
            return this.$refs['materialInfo'].showMateriaInfo(this.currentSelectRow)
          } else {
            return false
          }
        })
      },
      // 暂停报货
      saveStopSell() {
        let vm = this
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            let data = vm.form
            let postData = {
              strategyIds: this.strategyIds,
              item: {
                categoryCode: data.category.fid,
                categoryName: data.category.fname,
                productCode: data.product.fnumber,
                productName: data.product.fname,
                specCode: data.specCode,
                specNum: data.specNum,
                specName: data.product.fspecification,
                fbaseUnitIdfname: data.product.fbaseUnitIdfname,
                stopSell: data.stopSell
              }
            }
            await doMultiSetStopSellStrategy(postData)
            this.$baseMessage('价格策略保存成功', 'success')

            //刷新被选择的价格策略
            return this.$refs['materialInfo'].showMateriaInfo(this.currentSelectRow)

          } else {
            return false
          }
        })
      }
    },
  }
</script>
<style lang="scss" scoped>
.header_cond {
  height: 110px;
  margin-bottom: 20px;
  border-bottom: 1px solid #ddd;
  .header_cond_sub {
    display: flex;
    justify-content: space-between;
    .header_cond_fix {
      flex-shrink: 0;
    }
    .header_cond_part {
      display: flex;
      flex-shrink: 0;
    }
    .header_cond_btn {
      width: 100%;
      padding-left: 20px;
    }
  }
}
</style>
